<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书分类管理 - 知籁平台</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <style>
        .category-tree-container {
            max-height: 600px;
            overflow-y: auto;
        }
        .tree-item {
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 4px;
            margin-bottom: 4px;
        }
        .tree-item:hover {
            background-color: #f8f9fa;
        }
        .tree-item.active {
            background-color: #e9ecef;
        }
        .tree-toggle {
            width: 24px;
            display: inline-block;
            text-align: center;
        }
        .tree-level-1 { padding-left: 12px; }
        .tree-level-2 { padding-left: 36px; }
        .tree-level-3 { padding-left: 60px; }
        .book-count {
            color: #6c757d;
            font-size: 0.85rem;
        }
    </style>
</head>
<body>
    <!-- 页面头部 -->
    <header th:replace="common/header :: header"></header>

    <div class="container-fluid mt-4">
        <div class="row">
            <!-- 左侧分类树 -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">分类树</h5>
                        <button class="btn btn-primary btn-sm" id="addRootCategoryBtn">
                            <i class="fa fa-plus"></i> 添加一级分类
                        </button>
                    </div>
                    <div class="card-body category-tree-container">
                        <div id="categoryTree" class="pb-2">
                            <div class="text-center py-4">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="sr-only">加载中...</span>
                                </div>
                                <p class="mt-2">正在加载分类数据...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧分类详情 -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">分类详情</h5>
                        <div>
                            <button class="btn btn-success btn-sm mr-2" id="addSubCategoryBtn" style="display: none;">
                                <i class="fa fa-plus"></i> 添加子分类
                            </button>
                            <button class="btn btn-primary btn-sm mr-2" id="editCategoryBtn" style="display: none;">
                                <i class="fa fa-edit"></i> 编辑分类
                            </button>
                            <button class="btn btn-danger btn-sm" id="deleteCategoryBtn" style="display: none;">
                                <i class="fa fa-trash"></i> 删除分类
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div id="categoryDetail">
                            <div class="text-center py-5">
                                <p class="text-muted">请选择左侧的分类查看详情</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 分类下的图书列表 -->
                <div class="card mt-4" id="bookListCard" style="display: none;">
                    <div class="card-header">
                        <h5 class="mb-0">分类下的图书</h5>
                    </div>
                    <div class="card-body">
                        <div id="bookList">
                            <div class="text-center py-4">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="sr-only">加载中...</span>
                                </div>
                                <p class="mt-2">正在加载图书数据...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
                            </div>
                        </div>
    
    <!-- 添加/编辑分类模态框 -->
    <div class="modal fade" id="categoryModal" tabindex="-1" aria-labelledby="categoryModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="categoryModalLabel">添加分类</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="categoryForm">
                        <input type="hidden" id="categoryId">
                        <input type="hidden" id="parentId" value="0">
                        <input type="hidden" id="level" value="1">
                        
                        <div class="form-group">
                            <label for="categoryName">分类名称</label>
                            <input type="text" class="form-control" id="categoryName" required>
                        </div>
                        <div class="form-group">
                            <label for="description">分类描述</label>
                            <textarea class="form-control" id="description" rows="3"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="sort">排序</label>
                            <input type="number" class="form-control" id="sort" value="0">
                            <small class="form-text text-muted">数字越小越靠前</small>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveCategoryBtn">保存</button>
                </div>
            </div>
                            </div>
                        </div>
    
    <!-- 确认删除模态框 -->
    <div class="modal fade" id="confirmDeleteModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>确定要删除该分类吗？此操作不可撤销。</p>
                            </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
                </div>
            </div>
            </div>
        </div>
        
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
        <script>
        $(document).ready(function() {
            let currentCategoryId = null;
            
            // 加载分类树
            function loadCategoryTree() {
                $('#categoryTree').html(`
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="sr-only">加载中...</span>
                        </div>
                        <p class="mt-2">正在加载分类数据...</p>
                    </div>
                `);
                
                $.ajax({
                    url: '/api/categories/tree',
                    type: 'GET',
                    success: function(response) {
                        if (response.status === 200) {
                            renderCategoryTree(response.data);
                        } else {
                            $('#categoryTree').html(`
                                <div class="alert alert-danger">
                                    加载分类失败：${response.message}
                                </div>
                            `);
                        }
                    },
                    error: function() {
                        $('#categoryTree').html(`
                            <div class="alert alert-danger">
                                网络错误，请稍后重试
                            </div>
                        `);
                    }
                });
            }
            
            // 渲染分类树
            function renderCategoryTree(categories) {
                if (!categories || categories.length === 0) {
                    $('#categoryTree').html('<div class="alert alert-info">暂无分类数据</div>');
                    return;
                }
                
                let html = '';
                categories.forEach(function(category) {
                    html += renderCategoryItem(category, 1);
                });
                
                $('#categoryTree').html(html);
                bindTreeEvents();
            }
            
            // 渲染单个分类项
            function renderCategoryItem(category, level) {
                const hasChildren = category.children && category.children.length > 0;
                const toggleIcon = hasChildren ? 
                    '<i class="fa fa-caret-right"></i>' : 
                    '<span class="tree-toggle"></span>';
                
                let html = `
                    <div class="tree-item tree-level-${level}" data-id="${category.categoryId}">
                        <span class="tree-toggle">${toggleIcon}</span>
                        <span class="category-name">${category.categoryName}</span>
                        <span class="book-count ml-2">(${category.bookCount || 0})</span>
                    </div>
                `;
                
                if (hasChildren) {
                    html += '<div class="children" style="display: none;">';
                    category.children.forEach(function(child) {
                        html += renderCategoryItem(child, level + 1);
                    });
                    html += '</div>';
                }
                
                return html;
            }
            
            // 绑定树事件
            function bindTreeEvents() {
                // 点击分类项
                $('.tree-item').click(function(e) {
                    e.stopPropagation();
                    const categoryId = $(this).data('id');
                    $('.tree-item').removeClass('active');
                    $(this).addClass('active');
                    loadCategoryDetail(categoryId);
                });
                
                // 点击展开/折叠
                $('.tree-toggle').click(function(e) {
                    e.stopPropagation();
                    const parent = $(this).parent();
                    const children = parent.next('.children');
                    
                    if (children.length > 0) {
                        if (children.is(':visible')) {
                            children.hide();
                            $(this).html('<i class="fa fa-caret-right"></i>');
                        } else {
                            children.show();
                            $(this).html('<i class="fa fa-caret-down"></i>');
                        }
                    }
                });
            }
            
            // 加载分类详情
            function loadCategoryDetail(categoryId) {
                currentCategoryId = categoryId;
                
                $('#categoryDetail').html(`
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="sr-only">加载中...</span>
                        </div>
                        <p class="mt-2">正在加载分类详情...</p>
                    </div>
                `);
                
                // 显示操作按钮
                $('#addSubCategoryBtn, #editCategoryBtn, #deleteCategoryBtn').show();
                
                $.ajax({
                    url: `/api/categories/${categoryId}`,
                    type: 'GET',
                    success: function(response) {
                        if (response.status === 200) {
                            renderCategoryDetail(response.data);
                            loadCategoryBooks(categoryId);
                        } else {
                            $('#categoryDetail').html(`
                                <div class="alert alert-danger">
                                    加载分类详情失败：${response.message}
                                </div>
                            `);
                        }
                    },
                    error: function() {
                        $('#categoryDetail').html(`
                            <div class="alert alert-danger">
                                网络错误，请稍后重试
                            </div>
                        `);
                    }
                });
            }
            
            // 渲染分类详情
            function renderCategoryDetail(category) {
                const levelText = {
                    1: '一级分类',
                    2: '二级分类',
                    3: '三级分类'
                }[category.level] || `${category.level}级分类`;
                
                const html = `
                    <div class="row">
                        <div class="col-md-12">
                            <h4>${category.categoryName}</h4>
                            <p class="text-muted">
                                ${levelText} | 
                                图书数量：${category.bookCount || 0} | 
                                排序值：${category.sort || 0}
                            </p>
                            <hr>
                            <h5>分类描述</h5>
                            <p>${category.description || '暂无描述'}</p>
                        </div>
                    </div>
                `;
                
                $('#categoryDetail').html(html);
            }
            
            // 加载分类下的图书
            function loadCategoryBooks(categoryId) {
                $('#bookListCard').show();
                $('#bookList').html(`
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="sr-only">加载中...</span>
                        </div>
                        <p class="mt-2">正在加载图书数据...</p>
                    </div>
                `);
                
                // 这里应该调用后端API获取分类下的图书
                // 此处为模拟实现
                setTimeout(function() {
                    // 如果有实际API，应该改为真实请求
                    const mockBooks = [];
                    if (mockBooks.length > 0) {
                        let html = '<div class="row">';
                        mockBooks.forEach(function(book) {
                            html += `
                                <div class="col-md-4 mb-4">
                                    <div class="card">
                                        <img src="${book.coverUrl}" class="card-img-top" alt="${book.title}">
                                        <div class="card-body">
                                            <h5 class="card-title">${book.title}</h5>
                                            <p class="card-text text-muted">${book.author}</p>
                                            <a href="/books/${book.bookId}" class="btn btn-sm btn-primary">查看详情</a>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                        html += '</div>';
                        $('#bookList').html(html);
                    } else {
                        $('#bookList').html('<div class="alert alert-info">该分类下暂无图书</div>');
                    }
                }, 1000);
            }
            
            // 添加一级分类按钮点击事件
            $('#addRootCategoryBtn').click(function() {
                $('#categoryModalLabel').text('添加一级分类');
                $('#categoryForm')[0].reset();
                $('#categoryId').val('');
                $('#parentId').val(0);
                $('#level').val(1);
                $('#categoryModal').modal('show');
            });
            
            // 添加子分类按钮点击事件
            $('#addSubCategoryBtn').click(function() {
                if (!currentCategoryId) return;
                
                $.ajax({
                    url: `/api/categories/${currentCategoryId}`,
                    type: 'GET',
                    success: function(response) {
                        if (response.status === 200) {
                            const parentCategory = response.data;
                            if (parentCategory.level >= 3) {
                                alert('最多支持三级分类');
                                return;
                            }
                            
                            $('#categoryModalLabel').text(`添加"${parentCategory.categoryName}"的子分类`);
                            $('#categoryForm')[0].reset();
                            $('#categoryId').val('');
                            $('#parentId').val(parentCategory.categoryId);
                            $('#level').val(parentCategory.level + 1);
                            $('#categoryModal').modal('show');
                        }
                    }
                });
            });
            
            // 编辑分类按钮点击事件
            $('#editCategoryBtn').click(function() {
                if (!currentCategoryId) return;
                
                $.ajax({
                    url: `/api/categories/${currentCategoryId}`,
                    type: 'GET',
                    success: function(response) {
                        if (response.status === 200) {
                            const category = response.data;
                            $('#categoryModalLabel').text('编辑分类');
                            $('#categoryId').val(category.categoryId);
                            $('#parentId').val(category.parentId);
                            $('#level').val(category.level);
                            $('#categoryName').val(category.categoryName);
                            $('#description').val(category.description);
                            $('#sort').val(category.sort || 0);
                            $('#categoryModal').modal('show');
                        }
                    }
                });
            });
            
            // 删除分类按钮点击事件
            $('#deleteCategoryBtn').click(function() {
                if (!currentCategoryId) return;
                $('#confirmDeleteModal').modal('show');
            });
            
            // 确认删除按钮点击事件
            $('#confirmDeleteBtn').click(function() {
                if (!currentCategoryId) return;
                
                $.ajax({
                    url: `/api/categories/${currentCategoryId}`,
                    type: 'DELETE',
                    success: function(response) {
                        if (response.status === 200) {
                            $('#confirmDeleteModal').modal('hide');
                            alert('删除成功');
                            loadCategoryTree();
                            $('#categoryDetail').html('<div class="text-center py-5"><p class="text-muted">请选择左侧的分类查看详情</p></div>');
                            $('#bookListCard').hide();
                            $('#addSubCategoryBtn, #editCategoryBtn, #deleteCategoryBtn').hide();
                            currentCategoryId = null;
                        } else {
                            alert('删除失败：' + response.message);
                        }
                    },
                    error: function() {
                        alert('网络错误，请稍后重试');
                    }
                });
            });
            
            // 保存分类按钮点击事件
            $('#saveCategoryBtn').click(function() {
                const categoryId = $('#categoryId').val();
                const category = {
                    categoryName: $('#categoryName').val(),
                    description: $('#description').val(),
                    parentId: parseInt($('#parentId').val()),
                    level: parseInt($('#level').val()),
                    sort: parseInt($('#sort').val())
                };
                
                if (!category.categoryName) {
                    alert('请输入分类名称');
                    return;
                }
                
                const url = categoryId ? 
                    `/api/categories/${categoryId}` : 
                    '/api/categories';
                    
                const method = categoryId ? 'PUT' : 'POST';
                
                $.ajax({
                    url: url,
                    type: method,
                    contentType: 'application/json',
                    data: JSON.stringify(category),
                    success: function(response) {
                        if (response.status === 200) {
                            $('#categoryModal').modal('hide');
                            alert(categoryId ? '更新成功' : '添加成功');
                            loadCategoryTree();
                            
                            if (categoryId && categoryId === currentCategoryId) {
                                loadCategoryDetail(categoryId);
                            }
                        } else {
                            alert((categoryId ? '更新' : '添加') + '失败：' + response.message);
                        }
                    },
                    error: function() {
                        alert('网络错误，请稍后重试');
                    }
                });
            });
            
            // 初始加载分类树
            loadCategoryTree();
            });
        </script>
</body>
</html> 